package com.pig4cloud.pigx.order.common.mq;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pig4cloud.pigx.common.core.constant.enums.OrderStatusEnum;
import com.pig4cloud.pigx.order.api.entity.OrderInfo;
import com.pig4cloud.pigx.order.service.OrderInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@AllArgsConstructor
@RocketMQMessageListener(topic = "shop-order-pay-time-out", consumerGroup = "shop-order-group")
public class ShopOrderPayTimeOutListener implements RocketMQListener<String> {

	private final OrderInfoService orderInfoService;

	/**
	 * 处理商城订单支付超时
	 * @param id
	 */
	@Override
	public void onMessage(String id) {
		log.info("商城订单超时回调: {}", id);
		try {
			Long orderId = Long.parseLong(id);
			OrderInfo order = orderInfoService.getById(orderId);
			if (order != null) {
				if (order.getOrderStatus().equals(OrderStatusEnum.PENDING.getType())) {
					// 待付款状态的场合, 只更新状态为已取消
					OrderInfo record = new OrderInfo();
					record.setId(orderId);
					record.setOrderStatus(OrderStatusEnum.CANCELED.getType());
					record.setCancelReason("超时支付");
					orderInfoService.updateById(record);
					log.info("已取消订单:" + orderId);
				}
				else {
					log.info("当前订单:" + orderId + "不是待支付状态,状态已变更为:" + order.getOrderStatus());
				}
			}
			else {
				log.info("不存在当前订单:" + orderId + "无法做超时处理");
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
